import styled from 'styled-components';

export default function useMemoComp() {
  /**
   * useMemo:
   * 入参:
   * 回调函数:Function：返回需要缓存的值
   * 依赖项:Array：依赖项发生变化时，回调函数会重新执行(执行时机跟useEffect类似)返回值
   * 返回值：返回需要缓存的值(返回之后就不是函数了)
   * 注意点：如果依赖项是个空数组，那么 useMemo 的回调函数会执行一次；指定依赖项，当依赖项发生变化时， useMemo 的回调函数会执行；不指定依赖项，不推荐这么用，因为每次渲染和更新都会执行
   */
  const [search, setSearch] = useState('');
  const [goods, setGoods] = useState([
    { id: 1, name: '苹果', price: 3, count: 1 },
    { id: 2, name: '栗子', price: 20, count: 1 },
    { id: 3, name: '橘子', price: 2, count: 1 },
  ]);
  const handleAdd = (id: number) => {
    setGoods(goods.map((item) => (item.id === id ? { ...item, count: item.count + 1 } : item)));
  };
  const handleSub = (id: number) => {
    setGoods(goods.map((item) => (item.id === id ? { ...item, count: item.count - 1 } : item)));
  };
  // const total = () => {
  //   console.log('total');
  //   //例如很复杂的计算逻辑
  //   return goods.reduce((total, item) => total + item.price * item.count, 0);
  // };

  const memoTotal = useMemo(()=>{
    console.log('total');
     return goods.reduce((total, item) => total + item.price * item.count, 0);
  },[]); // 传空数组就只触发一次
  const [visible,setVisble] = useState(true);
  return (
    <Wrapper>
      <div className="useMemo">
        <h1>父组件</h1>
        <button onClick={()=>setVisble(!visible)}>卸载组件</button>
        <input type="text" value={search} onChange={(e) => setSearch(e.target.value)} />
        <table border={1} cellPadding={5} cellSpacing={0}>
          <thead>
            <tr>
              <th>商品名称</th>
              <th>商品价格</th>
              <th>商品数量</th>
            </tr>
          </thead>
          <tbody>
            {goods.map((item) => (
              <tr key={item.id}>
                <td>{item.name}</td>
                <td>{item.price * item.count}</td>
                <td>
                  <button onClick={() => handleAdd(item.id)}>+</button>
                  <span>{item.count}</span>
                  <button onClick={() => handleSub(item.id)}>-</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {/* <h2>总价：{total()}</h2> */}
        {
          visible && <h2>总价：{memoTotal}</h2> 
        }
      </div>
    </Wrapper>
  );
}
const Wrapper = styled.div`
  .useMemo {
    color: #000;
  }
`;
